//
//  HomeViewController.m
//  ManageMoney
//
//  Created by epwk on 15/9/7.
//  Copyright (c) 2015年 db. All rights reserved.
//

#import "HomeViewController.h"
#import "EPLoginViewController.h"
#import "PersonalCenterController.h"
#import "WebFileViewController.h"
#import "PayMethodsController.h"
#import "SearchHistoryController.h"


@interface HomeViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *adsScrollView;
@property (strong, nonatomic) NSMutableArray *adsArray;//广告
@property (strong, nonatomic) NSTimer *scrollViewTimer;
@property (strong, nonatomic) UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLab;
@property (weak, nonatomic) IBOutlet UIImageView *twoCodeImg;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    [self createRightBarButtonTitle:@"二维码"];
    self.navigationItem.leftBarButtonItem.customView.hidden = YES;
    self.navigationView.hidden = YES;
    
    _userNameLab.userInteractionEnabled = YES;
    [_userNameLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toLoginAction)]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUserDataAction:) name:RefreshUserData object:nil];
    
    [_twoCodeImg.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTwoCodeView)]];
    
    
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    
    [self.scrollView setContentSize:CGSizeMake(ScreenWith, 600)];
    
    self.adsArray = [NSMutableArray array];
    
    //广告  视图
    if (([[NSFileManager defaultManager] fileExistsAtPath:HomeAdsList])) {
        NSArray *ary = [NSKeyedUnarchiver unarchiveObjectWithFile:HomeAdsList];
        [_adsArray removeAllObjects];
        [_adsArray addObjectsFromArray:ary];
        [self setAdsView:_adsArray];
    }
    
    [self.adsArray addObjectsFromArray:@[@{@"ad_file":@"1"},@{@"ad_file":@"1"},@{@"ad_file":@"1"},@{@"ad_file":@"1"},@{@"ad_file":@"1"}]];
    [self setAdsView:_adsArray];
    
    
    if ([UserDefaults boolForKey:kDidLogin]) {
        NSString *string = CheckNull(UserInfo[@"NAME"]);
        string = [string stringByAppendingFormat:@"%@",@""];
        _userNameLab.text = string;
    }else
    {
        _userNameLab.text = @"未登录";
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    if (self.scrollViewTimer != nil)
    {
        [self.scrollViewTimer invalidate];
        self.scrollViewTimer = nil;
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    if (self.scrollViewTimer == nil)
    {
        self.scrollViewTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
    }
    
}
//隐藏 二维码视图
-(void)hideTwoCodeView
{
    _twoCodeImg.superview.hidden = YES;
}
-(void)setAdsView:(NSArray *)adsArray
{
    
    [self initContentView];
    if (self.pageControl) {
        [self.pageControl removeFromSuperview];
        self.pageControl = nil;
    }
    int count = (int)adsArray.count;
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(ScreenWith - count*30, 150*ScreenWith/320 + 20 - 30,count*30 , 20)];
    [self.pageControl setCurrentPageIndicatorTintColor:[UIColor colorWithHexString:@"f74d4d"]];
    [self.pageControl setPageIndicatorTintColor:[UIColor whiteColor]];
    self.pageControl.numberOfPages = [self.adsArray count];
    self.pageControl.currentPage = 0;
    [self.adsScrollView.superview addSubview:self.pageControl];
    
}

-(void)initContentView
{
    
    int adsCount = (int)[self.adsArray count];
    
    for(int i=0;i<adsCount;i++)
    {
        NSString *str=[[self.adsArray objectAtIndex:i] objectForKey:@"ad_file"];
        
        NSString *adsImageStr = str;
        NSURL *url2=[NSURL URLWithString:adsImageStr];
        CGRect frame=CGRectMake(ScreenWith*i + ScreenWith, 0,ScreenWith, 150*ScreenWith/320);
        if (adsCount==1) {
            frame=CGRectMake(ScreenWith*i, 0,ScreenWith, 150*ScreenWith/320);
        }
        
        
        UIImageView *contentImageView = [[UIImageView alloc]initWithFrame:frame];
        [contentImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ic_ad%d.png",i]]];
//        [contentImageView sd_setImageWithURL:url2 placeholderImage:PlaceholderImage];
        contentImageView.backgroundColor = [UIColor clearColor];
        contentImageView.tag = i;
        [self.adsScrollView addSubview:contentImageView];
        contentImageView.backgroundColor=[UIColor redColor];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adsImgtap:)];
        [contentImageView addGestureRecognizer:tap];
        [contentImageView setUserInteractionEnabled:YES];
    }
    if (adsCount <=1)
    {
        self.adsScrollView.scrollEnabled = NO;
        self.pageControl.hidden = YES;
        
    }
    else
    {
        self.adsScrollView.scrollEnabled = YES;
        self.pageControl.hidden = NO;
        self.adsScrollView.contentSize = CGSizeMake(ScreenWith*adsCount, 150*ScreenWith/320);
        self.pageControl.numberOfPages = adsCount;
        //        [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
        if (self.scrollViewTimer != nil)
        {
            [self.scrollViewTimer invalidate];
            self.scrollViewTimer = nil;
        }
        self.scrollViewTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
        
        // 取数组最后一张图片 放在第0页
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *str=[[self.adsArray objectAtIndex:([self.adsArray count]-1)] objectForKey:@"ad_file"];
        
        NSString *adsImageStr = str;
        NSURL *urlImg=[NSURL URLWithString:adsImageStr];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ic_ad%d.png",5]]];
//        [imageView sd_setImageWithURL:urlImg placeholderImage:PlaceholderImage];
        imageView.frame = CGRectMake(0, 0, ScreenWith, 150*ScreenWith/320); // 添加最后1页在首页 循环
        [self.adsScrollView addSubview:imageView];
        
        
        // 取数组第一张图片 放在最后1页
        UIImageView *imageView1 = [[UIImageView alloc] init];
        NSString *str1=[[self.adsArray objectAtIndex:0] objectForKey:@"ad_file"];
        NSURL *urlImg1=[NSURL URLWithString:str1];
        [imageView1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ic_ad%d.png",0]]];
//        [imageView1 sd_setImageWithURL:urlImg1 placeholderImage:PlaceholderImage];
        imageView1.frame = CGRectMake(ScreenWith * ([self.adsArray count] + 1) , 0, ScreenWith, 150*ScreenWith/320); // 添加第1页在最后 循环
        [self.adsScrollView addSubview:imageView1];
        
        [self.adsScrollView setContentSize:CGSizeMake(ScreenWith * ([self.adsArray count] + 2), self.adsScrollView.frame.size.height)]; //  +上第1页和第4页  原理：4-[1-2-3-4]-1
        [self.adsScrollView setContentOffset:CGPointMake(ScreenWith, 0)];
        
//        [self.adsScrollView scrollRectToVisible:CGRectMake(ScreenWith,0,ScreenWith,self.adsScrollView.frame.size.height) animated:NO]; // 默认从序号1位置放第1页 ，序号0位置位置放第4页
    }
    
    
}

-(void)adsImgtap:(UITapGestureRecognizer *)tap
{
    UIImageView *imgView = (UIImageView *)tap.view;
    NSInteger index = imgView.tag;
    NSLog(@"---%ld",index);
    
}

// 定时器 绑定的方法
- (void)runTimePage
{
    
    CGFloat pageWidth = ScreenWith;
    int page = floor((self.adsScrollView.contentOffset.x - pageWidth / 2) /pageWidth) +1;
    page = page+1;
    if (page > [self.adsArray count])
    {
        page = 1;
    }
    self.pageControl.currentPage = page;
    CGRect frame = self.adsScrollView.frame;
    frame.origin.x = frame.size.width * page;
    [self.adsScrollView scrollRectToVisible:frame animated:YES];
    
//        int page = self.pageControl.currentPage; // 获取当前的page
//        [self.adsScrollView scrollRectToVisible:CGRectMake(320*(page+1),0,320,460) animated:NO]; // 触摸pagecontroller那个点点 往后翻一页 +1
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    
    if (scrollView == self.adsScrollView)
    {
        
        if (self.scrollViewTimer != nil)
        {
            [self.scrollViewTimer invalidate];
            self.scrollViewTimer = nil;
        }
        self.scrollViewTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
        
        //        CGFloat pageWidth = self.adsScrollView.frame.size.width;
        //        int page = floor((self.adsScrollView.contentOffset.x - pageWidth / 2) /pageWidth) +1;
        //        self.pageControl.currentPage = page;
        
        CGFloat pagewidth = ScreenWith;
        int page = floor((self.adsScrollView.contentOffset.x - pagewidth/([self.adsArray count] + 2))/pagewidth)+1;
        page --;  // 默认从第二页开始
        self.pageControl.currentPage = page;
        
    }
    
    
    
}

// scrollview 委托函数
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pagewidth = ScreenWith;
    int currentPage = floor((self.adsScrollView.contentOffset.x - pagewidth/ ([self.adsArray count]+2)) / pagewidth) + 1;
    //    int currentPage_ = (int)self.scrollView.contentOffset.x/320; // 和上面两行效果一样
    //    NSLog(@"currentPage_==%d",currentPage_);
    if (currentPage == 0)
    {
        [self.adsScrollView scrollRectToVisible:CGRectMake(ScreenWith * [self.adsArray count],0,ScreenWith,self.adsScrollView.frame.size.height) animated:NO]; // 序号0 最后1页
    }
    else if (currentPage==([self.adsArray count]+1))
    {
        [self.adsScrollView scrollRectToVisible:CGRectMake(ScreenWith,0,ScreenWith,self.adsScrollView.frame.size.height) animated:NO]; // 最后+1,循环第1页
    }
}


- (IBAction)homeItemsAction:(id)sender {
    UIButton *btn = (UIButton *)sender;

    
    switch (btn.tag) {
        case 0:
        {
            if (![UserDefaults boolForKey:kDidLogin]) {
                [self toLoginAction];
                return;
            }
            PayMethodsController *ctr = [[PayMethodsController alloc] initWithNibName:@"PayMethodsController" bundle:nil];
            ctr.title = @"充值";
            ctr.payType = 1;
            [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        case 1:
        {
                WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
                [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        case 2:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
            [self.navigationController pushViewController:ctr animated:YES];
        }

            break;
        case 3:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
            [self.navigationController pushViewController:ctr animated:YES];
        }

            break;
        case 4:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
            [self.navigationController pushViewController:ctr animated:YES];
        }

            break;
        case 5:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
            [self.navigationController pushViewController:ctr animated:YES];
        }

            break;
        case 6:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"吃喝玩乐";
            ctr.fileUrl = @"http://www.meituan.com";
            [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        case 7:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"商旅出行";
            ctr.fileUrl = @"http://www.ctrip.com";
            [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        case 8:
        {
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.title = @"";
            ctr.fileUrl = @"";
            [self.navigationController pushViewController:ctr animated:YES];
        }

            break;
            
        default:
            break;
    }
}



-(void)viewWillAppear:(BOOL)animated
{
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"titlebar_64"] forBarMetrics:UIBarMetricsDefault];
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated
{
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

//充值  归集  查询  个人中心
- (IBAction)personalCenterAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    switch (btn.tag) {
        case 1:
        {
            if (![UserDefaults boolForKey:kDidLogin]) {
                [self toLoginAction];
                return;
            }
            PayMethodsController *ctr = [[PayMethodsController alloc] initWithNibName:@"PayMethodsController" bundle:nil];
            ctr.title = @"钱包归集";
            ctr.payType = 0;
            [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        case 2:
        {
            if (![UserDefaults boolForKey:kDidLogin]) {
                [self toLoginAction];
                return;
            }
            PayMethodsController *ctr = [[PayMethodsController alloc] initWithNibName:@"PayMethodsController" bundle:nil];
            ctr.title = @"账户查询";
            ctr.payType = 2;
            [self.navigationController pushViewController:ctr animated:YES];
            
            
        }
            break;
        case 3:
        {
            if (![UserDefaults boolForKey:kDidLogin]) {
                [self toLoginAction];
                return;
            }
            PersonalCenterController *ctr = [[PersonalCenterController alloc] initWithNibName:@"PersonalCenterController" bundle:nil];
            [self.navigationController pushViewController:ctr animated:YES];
        }
            break;
        default:
            break;
    }
    
}
//登陆成功 刷新数据
-(void)refreshUserDataAction:(NSNotification *)obj
{
    NSDictionary *dic = obj.object;
    if (CheckNull(dic) != nil) {
        NSString *string = CheckNull(dic[@"NAME"]);
         string = [string stringByAppendingFormat:@"%@",@""];
        _userNameLab.text = string;
    }else
    {
        _userNameLab.text = @"未登录";
    }
    
}
//二维码 显示
- (IBAction)codeAction:(id)sender {
    _twoCodeImg.superview.hidden = NO;
}
//登录
-(void)toLoginAction
{
    if ([UserDefaults boolForKey:kDidLogin]) {
        return;
    }
    EPLoginViewController *ctr = [[EPLoginViewController alloc] initWithNibName:@"EPLoginViewController" bundle:nil];
    [self.navigationController pushViewController:ctr animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
